/**
 * @Author: wangliuyang
 * @Date: 2021/9/7 17:01
 * @Description:
 */
public class Solution_96 {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        return numDecoding(s, 0);
    }

    public int numDecoding(String s, int index) {
        if (index == s.length()) {
            return 1;
        }
        if (s.charAt(index) == '0') {
            return 0;
        }
        if (s.charAt(index) == '1') {
            return numDecoding(s, index + 1) + (index + 1 < s.length() ? numDecoding(s, index + 2) : 0);
        }
        if (s.charAt(index) == '2') {
            return numDecoding(s, index + 1) + (index + 1 < s.length() && s.charAt(index + 1) >= '0' && s.charAt(index + 1) <= '6' ? numDecoding(s, index + 2) : 0);
        }
        return numDecoding(s, index + 1);
    }

    public int numDecodings2(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int[] dp = new int[s.length() + 1];
        dp[s.length()] = 1;
        for (int i = dp.length - 2; i >= 0; i--) {
            if (s.charAt(i) == '0'){
                dp[i] = 0;
                continue;
            }
            if (s.charAt(i) == '1'){
                dp[i] = dp[i + 1] + (i + 1 < s.length() ? dp[i + 2] : 0);
                continue;
            }
            if (s.charAt(i) == '2') {
                dp[i] = dp[i + 1] + (i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '6' ? dp[i + 2] : 0 );
                continue;
            }
            dp[i] = dp[i + 1];
        }
        return dp[0];
    }
}
